<?php

namespace App\Services;

use App\Models\User;
use App\Facades\Message;
use App\Models\ReportWork;
use App\Models\RPersonPost;
use Illuminate\Support\Str;
use App\Models\STaskCategory;
use App\Models\ProjectPerson;
use App\Models\TaskAssignment;
use App\Models\SReportWorkType;
use App\Models\RUserProjectauth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ReportService extends BaseService
{
    /**
     * 单人一天内正常工时最大允许填报小时数
     */
    const MAX_STANDARD_HOURS = 8;

    /**
     * 首页展示数据展示
     * 1 我的报工
     * 2 报工审批
     * 3 报工历史
     * @param int $type
     * @param array $parameters
     * @return array|void
     */
    public function index(int $type,array $parameters): array
    {
        switch ($type) {
            case 1:
                return $this->myReport($parameters);
            case 2:
                return $this->reportApproval($parameters);
            default:
                return $this->reportHistory($parameters);
        }
    }

    /**
     * 我的报工
     * 默认展示当天的报工
     * @param array $parameters
     * @return array
     */
    public function myReport(array $parameters): array
    {
        try{
            if (!isset($parameters['date']) || empty($parameters['date']))  {
                $parameters['date'] = date('Y-m-d');
            }

            $data = ReportWork::filter($parameters)
                ->where('user_id',auth('api')->user()->id)
                ->where('is_deleted',0)
                ->orderBy('report_date','desc')
                ->paginate(10)
                ->toArray();

            $total = $data['total'];

            //转换数据格式
            $data = array_map(function ($item){
                return [
                    'id'           => $item['report_uid'],
                    'title'        => $item['title'],
                    'project_name' => $item['project_name'],
                    'report_date'  => $item['report_date'],
                    'is_plan'      => $item['is_plan'],
                    'time'         => $item['standard_hours']
                        + $item['common_overtime_hours']
                        + $item['holiday_hours']
                        + $item['other_hours']
                        . 'h'
                ];
            },$data['data']);

            return customer_return_success('success',compact('total','data'));
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('我的报工异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 报工审批
     * 只展示未被审批的
     * @param array $parameters
     * @return array
     */
    public function reportApproval(array $parameters): array
    {
        try{
            $data = ReportWork::filter($parameters)
                ->where('user_id',auth('api')->user()->id)
                ->where('status_id',2)
                ->where('is_deleted',0)
                ->with([
                    'approver' => function($query){
                        return $query->with('person');
                    }
                ])
                ->whereExists(function ($query){
                    return $query->select(DB::raw(1))
                        ->from('r_user_projectauth')
                        ->where('r_user_projectauth.operation_id',190)
                        ->whereRaw('r_user_projectauth.project_id = report_work.project_id')
                        ->where('r_user_projectauth.user_id',auth('api')->user()->id);
                })
                ->orderBy('report_date','desc')
                ->whereNull('approver_time')
                ->paginate(10)
                ->toArray();

            $total = $data['total'];

            //转换数据格式
            $data = array_map(function ($item){
                return [
                    'id'           => $item['report_uid'],
                    'project_name' => $item['project_name'],
                    'title'        => $item['title'],
                    'report_date'  => $item['report_date'],
                    'is_plan'      => $item['is_plan'],
                    'time'         => $item['standard_hours']
                        + $item['common_overtime_hours']
                        + $item['holiday_hours']
                        + $item['other_hours']
                        . 'h',
                    'name'   => $item['approver']['person']['name'] ?? '',
                    'status' => $item['status_id']
                ];
            },$data['data']);

            return customer_return_success('success',compact('total','data'));
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('报工审批异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 展示除了今天的数据
     * @param array $parameters 报工历史
     * @return array
     */
    public function reportHistory(array $parameters): array
    {
        try{
            $data = ReportWork::filter($parameters)
                ->where('user_id',auth('api')->user()->id)
                ->where('is_deleted',0)
                ->with([
                    'approver' => function($query){
                        return $query->with('person');
                    }
                ])
                ->where('report_date','<',date('Y-m-d'))
                ->orderBy('report_date','desc')
                ->paginate(10)
                ->toArray();

            $total = $data['total'];

            //转换数据格式
            $data = array_map(function ($item){
                return [
                    'id'           => $item['report_uid'],
                    'name'         => $item['approver']['person']['name'] ?? '',
                    'project_name' => $item['project_name'],
                    'title'        => $item['title'],
                    'is_plan'      => $item['is_plan'],
                    'report_date'  => $item['report_date'],
                    'time'         => $item['standard_hours']
                        + $item['common_overtime_hours']
                        + $item['holiday_hours']
                        + $item['other_hours']
                        . 'h',
                    'status' => $item['status_id']
                ];
            },$data['data']);

            return customer_return_success('success',compact('total','data'));
        }catch (\Exception $exception) {
            Log::channel('api')
                ->info('报工历史异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 报工审核（包含批量审核和单个审核）
     * status = 1 表示通过 status = 0 表示驳回
     * 数据库中保存的 status_id 3 表示审核通过 4 表示审核不通过
     * @param array $parameters
     * @return mixed
     */
    public function approval(array $parameters)
    {
        try{
            $data = [
                'approver_time' => date('Y-m-d H:i:s'),
                'audit_opinion' => $parameters['comment'] ?? null,
                'status_id'     => $parameters['status'] == 1 ? 3 : 4
            ];

            ReportWork::whereIn('report_uid',$parameters['id'])
                ->update($data);

            $projectNames = ReportWork::whereIn('report_uid',$parameters['id'])
                ->pluck('project_name');

            foreach ($projectNames as $projectName) {
                Message::sendMessage('report_approve',2,[
                    'project' => $projectName,
                    'status'  => $parameters['status'] == 1 ? '审批通过' : '审批驳回'
                ]);
            }

            return customer_return_success('审核成功');
        }catch (\Exception $exception) {
            Log::channel('api')
                ->info('报工审批异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('审批失败，请稍后再试');
        }
    }

    /**
     * 审核记录
     * @param string $id
     * @return array
     */
    public function getApprovalProcess(string $id) : array
    {
        try {
            $data = ReportWork::where('report_uid',$id)
                ->with([
                    'approver' => function($query){
                        return $query->with('person');
                    }
                ])
                ->first();

            if (is_null($data)) {
                return customer_return_error('id 异常');
            }

            $data = $data->toArray();

            $user = User::where('id',$data['user_id'])
                ->first();

            if ($user) {
                $username = $user->person->name ?? '';
            }

            $details = [
                'report_date' => $data['report_date'],
                'name'        => $username ?? '',
            ];

            if (isset($data['approver_time'])
                && !empty($data['approver_time'])
                && isset($data['approver'])
                && !empty($data['approver'])) {
                $details['approver_date'] = $data['approver_time'];
                $details['approver']  = $data['approver']['person']['name'] ?? '';
                $details['notice']  = $data['audit_opinion'] ?? '';
            }

            return customer_return_success('success',$details);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('报工审批记录异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 获取到工作类型名称
     * @param int $typeId
     * @return mixed
     */
    public function getWorkTypeName(int $typeId)
    {
        return SReportWorkType::where('id',$typeId)
            ->value('name');
    }

    /**
     * 获取到任务类型的名称
     * @param int $typeId
     * @return string
     */
    public function getTaskTypeName(int $typeId) : string
    {
        return STaskCategory::where('id',$typeId)
            ->value('name');
    }

    /**
     * 获取到报工是计划内还是计划外报工
     * @param $reportId
     * @return int|array
     */
    public function getReportType($reportId)
    {
        $report = ReportWork::where('report_uid',$reportId)
            ->first();

        if (is_null($report)) {
            return customer_return_error('报工id异常，数据不存在');
        }

        return $report->is_plan;
    }

    /**
     * 获取到报工的详情信息
     * @param string $reportId
     * @return array
     */
    public function getReportDetails(string $reportId) : array
    {
        try{
            $type = $this->getReportType($reportId);

            if (is_array($type)) {
                return $type;
            }

            if ($type == 1) {
                $report = ReportWork::where('report_uid',$reportId)
                    ->first()
                    ->toArray();

                $details = [
                    'type'                  => $type,
                    'work_type'             => $report['type_id'],
                    'work_type_name'        => $this->getWorkTypeName($report['type_id']),
                    'category_id'           => $report['category_id'],
                    'project_name'          => $report['project_name'],
                    'project_id'            => $report['project_id'],
                    'task_name'             => $report['title'],
                    'task_id'               => $report['source_uids'],
                    'complete_percent'      => $report['complete_percent'],
                    'plan_hours'            => $report['plan_working_hours'],
                    'used_hours'            => $report['used_working_hours'],
                    'standard_hours'        => $report['standard_hours'],
                    'common_overtime_hours' => $report['common_overtime_hours'],
                    'holiday_hours'         => $report['holiday_hours'],
                    'other_hours'           => $report['other_hours'],
                    'comment'               => $report['comm'],
                    'work_report'           => $report['work_report'],
                ];
            } else {
                $report = ReportWork::where('report_uid',$reportId)
                    ->first()
                    ->toArray();

                $details = [
                    'type'                  => $type,
                    'work_type'             => $report['type_id'],
                    'work_type_name'        => $this->getWorkTypeName($report['type_id']),
                    'task_type'             => $report['category_id'],
                    'task_type_name'        => $this->getTaskTypeName($report['category_id']),
                    'title'                 => $report['title'],
                    'standard_hours'        => $report['standard_hours'],
                    'common_overtime_hours' => $report['common_overtime_hours'],
                    'holiday_hours'         => $report['holiday_hours'],
                    'other_hours'           => $report['other_hours'],
                    'complete_percent'      => $report['complete_percent'],
                    'project_name'          => $report['project_name'],
                    'project_id'            => $report['project_id'],
                    'work_report'           => $report['work_report'],
                    'comment'               => $report['comm'],
                ];
            }

            return customer_return_success('success',$details);
        } catch (\Exception $exception){
            Log::channel('api')
                ->info('报工详情异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 编辑报工数据
     * @param array $parameters
     * @return array
     */
    public function updateReport(array $parameters) :  array
    {
        try {
            $reportDate = ReportWork::where('report_uid',$parameters['report_id'])
                ->value('report_date');
            $todayUsedHours = $this->getReportHour($reportDate, 1, $parameters['report_id']);
            if($todayUsedHours > self::MAX_STANDARD_HOURS){
                $todayUsedHours = self::MAX_STANDARD_HOURS;
            }
            if(($parameters['standard_hours'] ?? 0.0) + $todayUsedHours > self::MAX_STANDARD_HOURS){
                return customer_return_error('其他任务已填报工时为：'.$todayUsedHours.'小时,剩余可填报工时不得超过'.(self::MAX_STANDARD_HOURS - $todayUsedHours).'小时');
            }

            $type = $this->getReportType($parameters['report_id']);

            if (is_array($type)) {
                return $type;
            }

            if ($type == 1) {
                ReportWork::where('report_uid',$parameters['report_id'])
                    ->update([
                        'type_id'               => $parameters['work_type'] ,
                        'category_id'           => $parameters['category_id'],
                        'project_name'          => $parameters['project_name'],
                        'title'                 => $parameters['task_name'],
                        'source_uids'           => $parameters['task_id'],
                        'complete_percent'      => $parameters['complete_percent'] ?? 0,
                        'plan_working_hours'    => $parameters['plan_hours'] ?? 0.0,
                        'used_working_hours'    => $parameters['used_hours'] ?? 0.0,
                        'standard_hours'        => $parameters['standard_hours'] ?? 0.0,
                        'common_overtime_hours' => $parameters['common_overtime_hours'] ?? 0.0,
                        'holiday_hours'         => $parameters['holiday_hours'] ?? 0.0,
                        'other_hours'           => $parameters['other_hours'] ?? 0.0,
                        'comm'                  => $parameters['comment'] ?? '',
                        'project_id'            => $parameters['project_id'],
                        'work_report'           => $parameters['work_report'] ?? '',
                    ]);
            } else {
                ReportWork::where('report_uid',$parameters['report_id'])
                    ->update([
                        'type_id'               => $parameters['work_type'],
                        'category_id'           => $parameters['task_type'],
                        'project_name'          => $parameters['project_name'],
                        'title'                 => $parameters['title'],
                        'complete_percent'      => $parameters['complete_percent'] ?? 0,
                        'standard_hours'        => $parameters['standard_hours'] ?? 0.0,
                        'common_overtime_hours' => $parameters['common_overtime_hours'] ?? 0.0,
                        'holiday_hours'         => $parameters['holiday_hours'] ?? 0.0,
                        'other_hours'           => $parameters['other_hours'] ?? 0.0,
                        'work_report'           => $parameters['work_report'] ?? '',
                        'comm'                  => $parameters['comment'] ?? '',
                        'project_id'            => $parameters['project_id'],
                    ]);
            }

            return customer_return_success('success',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('报工修改异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 删除报工数据
     * @param string $reportId
     * @return array
     */
    public function destroyReportDetails(string $reportId) : array
    {
        try{
            $report = ReportWork::where('report_uid',$reportId)
                ->first();

            if (is_null($report)) {
                return customer_return_error('报工id异常，数据不存在');
            }

            ReportWork::where('report_uid',$reportId)
                ->update([
                    'is_deleted' => 1
                ]);

            return customer_return_success('success',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('报工删除异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 创建计划内和计划外报工
     * @param array $parameters
     * @return array
     */
    public function createReport(array $parameters) : array
    {
        if ($parameters['report_type'] == 1) {
            return $this->createInPlanReport($parameters);
        } else {
            return $this->createOutPlanReport($parameters);
        }
    }

    public function getReportHour($date, $type = 1, $curReportUID = '')
    {
        try {
            switch ($type){
                case 1:
                    $reportColStr   = 'standard_hours';
                    break;
                case 2:
                    $reportColStr   = 'common_overtime_hours';
                    break;
                case 3:
                    $reportColStr   = 'holiday_hours';
                    break;
                case 4:
                    $reportColStr   = 'other_hours';
                    break;
                default:
                    $reportColStr ='standard_hours';
            }
            return ReportWork::whereDate('report_date',$date)
                ->where('user_id',auth('api')->user()->id)
                ->whereNotIn('report_uid',[$curReportUID])
                ->where('is_deleted',0)
                ->sum($reportColStr);
        }catch (\Exception $exception){
            Log::channel('api')
            ->info('查询已报工时操作异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 创建计划外报工
     * @param array $parameters
     * @return array
     */
    public function createOutPlanReport(array $parameters): array
    {
        try {
            $todayUsedHours = $this->getReportHour($parameters['date'], 1);
            if($todayUsedHours > self::MAX_STANDARD_HOURS){
                $todayUsedHours = self::MAX_STANDARD_HOURS;
            }
            if(($parameters['standard_hours'] ?? 0.0) + $todayUsedHours > self::MAX_STANDARD_HOURS){
                return customer_return_error('其他任务已填报工时为：'.$todayUsedHours.'小时,剩余可填报工时不得超过'.(self::MAX_STANDARD_HOURS - $todayUsedHours).'小时');
            }
//            $status = ReportWork::where('user_id',auth('api')->user()->id)
//                ->whereDate('report_date',$parameters['date'])
//                ->exists();
            $status = false; //计划外报工创建时不做重复性校验

            $date = $parameters['date'] .' '. date("H:i:s");

            if ($status) {
                ReportWork::whereDate('report_date',$parameters['date'])
                    ->where('user_id',auth('api')->user()->id)
                    ->update([
                        'type_id'               => $parameters['work_type'],
                        'category_id'           => $parameters['task_type'],
                        'project_name'          => $parameters['project_name'],
                        'title'                 => $parameters['title'],
                        'complete_percent'      => $parameters['complete_percent'] ?? 0,
                        'standard_hours'        => $parameters['standard_hours'] ?? 0.0,
                        'common_overtime_hours' => $parameters['common_overtime_hours'] ?? 0.0,
                        'holiday_hours'         => $parameters['holiday_hours'] ?? 0.0,
                        'other_hours'           => $parameters['other_hours'] ?? 0.0,
                        'work_report'           => $parameters['work_report'] ?? '',
                        'comm'                  => $parameters['comment'] ?? '',
                        'project_id'            => $parameters['project_id'],
                        'report_date'           => $date
                    ]);

                Message::sendMessage('report_fill',1,[
                    'project'  => $parameters['project_name'],
                    'task'     => $parameters['title'],
                ]);

                return customer_return_success('编辑成功');
            } else {
                ReportWork::insert([
                    'type_id'               => $parameters['work_type'],
                    'category_id'           => $parameters['task_type'],
                    'project_name'          => $parameters['project_name'],
                    'title'                 => $parameters['title'],
                    'complete_percent'      => $parameters['complete_percent'] ?? 0,
                    'standard_hours'        => $parameters['standard_hours'] ?? 0.0,
                    'common_overtime_hours' => $parameters['common_overtime_hours'] ?? 0.0,
                    'holiday_hours'         => $parameters['holiday_hours'] ?? 0.0,
                    'other_hours'           => $parameters['other_hours'] ?? 0.0,
                    'work_report'           => $parameters['work_report'] ?? '',
                    'comm'                  => $parameters['comment'] ?? '',
                    'project_id'            => $parameters['project_id'],
                    'user_id'               => auth('api')->user()->id,
                    'report_date'           => $date,
                    'report_uid'            => Str::uuid()->getHex(),
                    'status_id'             => 2,
                    'source_uids'           => '0',
                    'plan_working_hours'    => '0.0',
                    'used_working_hours'    => '0.0',
                    'is_deleted'            => 0,
                    'is_plan'               => 0,
                    'is_counted'            => 0,
                    'source_type'           => 5,
                ]);

                Message::sendMessage('report_fill',1,[
                    'project'  => $parameters['project_name'],
                    'task'     => $parameters['title'],
                ]);

                return customer_return_success('填报成功');
            }
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('计划外的报工操作异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 创建计划内的报工
     * @param array $parameters
     * @return array
     */
    public function createInPlanReport(array $parameters) : array
    {
        try {
            $todayUsedHours = $this->getReportHour($parameters['date'], 1);
            if($todayUsedHours > self::MAX_STANDARD_HOURS){
                $todayUsedHours = self::MAX_STANDARD_HOURS;
            }
            if(($parameters['standard_hours'] ?? 0.0) + $todayUsedHours > self::MAX_STANDARD_HOURS){
                return customer_return_error('其他任务已填报工时为：'.$todayUsedHours.'小时,剩余可填报工时不得超过'.(self::MAX_STANDARD_HOURS - $todayUsedHours).'小时');
            }

            $status = ReportWork::where('user_id',auth('api')->user()->id)
                ->whereDate('report_date',$parameters['date'])
                ->where('source_uids',$parameters['task_id'])
                ->where('is_deleted',0)
                ->exists();

            $date = $parameters['date'] .' '. date("H:i:s");

            if ($status) {
                ReportWork::whereDate('report_date',$parameters['date'])
                    ->where('user_id',auth('api')->user()->id)
                    ->limit(1)
                    ->update([
                        'type_id'               => $parameters['work_type'] ,
                        'category_id'           => $parameters['category_id'],
                        'project_name'          => $parameters['project_name'],
                        'title'                 => $parameters['task_name'],
                        'source_uids'           => $parameters['task_id'],
                        'complete_percent'      => $parameters['complete_percent'] ?? 0,
                        'plan_working_hours'    => $parameters['plan_hours'] ?? 0.0,
                        'used_working_hours'    => $parameters['used_hours'] ?? 0.0,
                        'standard_hours'        => $parameters['standard_hours'] ?? 0.0,
                        'common_overtime_hours' => $parameters['common_overtime_hours'] ?? 0.0,
                        'holiday_hours'         => $parameters['holiday_hours'] ?? 0.0,
                        'other_hours'           => $parameters['other_hours'] ?? 0.0,
                        'comm'                  => $parameters['comment'] ?? '',
                        'project_id'            => $parameters['project_id'],
                        'work_report'           => $parameters['work_report'] ?? '',
                        'report_date'           => $date
                    ]);

                Message::sendMessage('report_fill',1,[
                    'project'  => $parameters['project_name'],
                    'task'     => $parameters['task_name'],
                ]);

                return customer_return_success('编辑成功');
            } else {
                ReportWork::insert([
                    'type_id'               => $parameters['work_type'] ,
                    'category_id'           => $parameters['category_id'],
                    'project_name'          => $parameters['project_name'],
                    'title'                 => $parameters['task_name'],
                    'source_uids'           => $parameters['task_id'],
                    'complete_percent'      => $parameters['complete_percent'] ?? 0,
                    'plan_working_hours'    => $parameters['plan_hours'] ?? 0.0,
                    'used_working_hours'    => $parameters['used_hours'] ?? 0.0,
                    'standard_hours'        => $parameters['standard_hours'] ?? 0.0,
                    'common_overtime_hours' => $parameters['common_overtime_hours'] ?? 0.0,
                    'holiday_hours'         => $parameters['holiday_hours'] ?? 0.0,
                    'other_hours'           => $parameters['other_hours'] ?? 0.0,
                    'comm'                  => $parameters['comment'] ?? '',
                    'project_id'            => $parameters['project_id'],
                    'work_report'           => $parameters['work_report'] ?? '',
                    'user_id'               => auth('api')->user()->id,
                    'report_date'           => $date,
                    'report_uid'            => Str::uuid()->getHex()->toString(),
                    'is_deleted'            => 0,
                    'is_plan'               => 1,
                    'is_counted'            => 0,
                    'source_type'           => 1,
                    'status_id'             => 1
                ]);


                Message::sendMessage('report_fill',1,[
                    'project'  => $parameters['project_name'],
                    'task'     => $parameters['task_name'],
                ]);

                return customer_return_success('填报成功');
            }
        } catch (\Exception $exception){
            Log::channel('api')
                ->info('计划内的报工操作异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 获取项目任务或项目
     * 计划内报工 任务和项目
     * @param  $search
     * @return array
     */
    public function getProject($search) : array
    {
        try {
            $model = ProjectPerson::from('project_person as pp')
                ->select([
                    'po.id',
                    'po.name'
                ])
                ->Join('project as po',function ($join){
                    return $join->on('pp.project_id','=','po.id');
                })
                ->where('po.is_deleted',0)
                ->where('pp.user_id',auth()->user()->id);

            if (!empty($search)) {
                $model = $model->where('po.name','like','%'.$search.'%');
            }

            $data = $model
                ->paginate(30)
                ->map(function ($value){
                    return [
                        'id'    => $value->id,
                        'value' => $value->name
                    ];
                })
                ->toArray();

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('获取项目异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 根据项目id获取到任务
     * @param int $projectId
     * @return array
     */
    public function getTask(int $projectId) : array
    {
        try{
            $data = TaskAssignment::from('task_assignment as tass')
                ->join('task as task',function ($join){
                    return $join->on('tass.TaskUID','=','task.UID');
                })
                ->join('project as project',function ($join){
                    return $join->on('task.project_id','=','project.id');
                })
                ->where('project.is_archived',0)
                ->where('project.is_deleted',0)
                ->where('task.Milestone',0)
                ->where('tass.ResourceUID',auth('api')->user()->id)
                ->where('project.id',$projectId)
                ->whereIn('task.STATUS',[2,3,4,5])
                ->select([
                    'task.UID',
                    'task.Name',
                    'tass.plan_working_hours',
                    'tass.use_working_hours',
                    'task.category',
                    'task.PercentComplete'
                ])
                ->paginate(30)
                ->map(function ($value){
                    return [
                        'id'               => $value->UID,
                        'name'             => $value->Name,
                        'category_id'      => $value->category,
                        'plan_hours'       => (float) $value->plan_working_hours ?: 0.0,
                        'used_hours'       => (float) $value->use_working_hours ?: 0.0,
                        'complete_percent' => (float) $value->PercentComplete
                    ];
                })
                ->toArray();

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('获取任务异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 获取到工作类型
     * @return array
     */
    public function getWorkType() : array
    {
        try{
            $postIdArray = RPersonPost::where('person_id',136)
                ->pluck('post_id')
                ->toArray();

            if (!empty($postIdArray)) {
                $types = SReportWorkType::from('s_report_work_type as r')
                    ->join('r_post_report_type as p',function ($join){
                        return $join->on('r.id','=','p.type_id');
                    })
                    ->whereIn('p.post_id',$postIdArray)
                    ->select([
                        'r.id',
                        'r.name'
                    ])
                    ->get()
                    ->map(function ($value){
                        return [
                            'id'    => $value->id,
                            'value' => $value->name
                        ];
                    })
                    ->toArray();
            }

            if (!isset($types) || empty($types)) {
                $types = SReportWorkType::orderBy('ord')
                    ->select([
                        'id',
                        'name'
                    ])
                    ->get()
                    ->map(function ($value){
                        return [
                            'id'    => $value->id,
                            'value' => $value->name
                        ];
                    })
                    ->toArray();
            }

            return customer_return_success('success',$types);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('获取工作类型异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 获取任务类型
     * @return array
     */
    public function getTaskType() : array
    {
        try{
            $data = STaskCategory::orderBy('ord','asc')
                ->get()
                ->map(function ($value){
                    $index = strlen($value['ord']) / 2;
                    $value['parent_id']  = substr($value['ord'],0,2 * ($index-1));

                    return $value;
                })
                ->toArray();

            $details = custom_array_tree($data,'ord','parent_id','child');

            //整理数据格式
            $details = $this->formatTaskType($details);

            return customer_return_success('success',$details);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('获取任务类型异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * tree 格式化任务类型数据
     * @param array $data
     * @return array
     */
    public function formatTaskType(array $data): array
    {
        $details = [];

        $data = array_values($data);

        foreach ($data as $key => $value) {
            if (isset($value['child'])) {
                $details[$key] = [
                    'id'    => $value['id'],
                    'value' => $value['name'],
                ];

                $details[$key]['child'] = $this->formatTaskType($value['child']);
            } else {
                $details[] = [
                    'id'    => $value['id'],
                    'value' => $value['name'],
                ];
            }
        }

        return $details;
    }

    /**
     * 判断报工是否已经填报
     * @param string $date
     * @return array
     */
    public function getReportStatus(string $date) : array
    {
        $status = ReportWork::where('user_id',auth('api')->user()->id)
            ->whereDate('report_date',$date)
            ->exists();

        if ($status) {
            return customer_return_error('报工已填报');
        } else {
            return customer_return_success('success');
        }
    }
}
